<?php

namespace App\Repository;

use GuzzleHttp\Client;

class WechatWork
{
    protected $app;
    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
        $this->app = \EasyWeChat::work();
    }

    //获取用户连接
    public function getexternalContact()
    {
        $token = $this->app->access_token->getToken();
        $result = $this->client->post('https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition/list_link?access_token=' . $token['access_token'], [
            'json' => [
                "limit" => 100,
            ]
        ]);
    }

    /**
     * @param $linkName
     * @param $userIds
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException{
     * "errcode": 0,
     * "errmsg": "ok",
     * "link":{
     * "link_id":"LINK_ID",
     * "link_name":"获客链接1号",
     * "url":"URL",
     * "create_time":1667232000
     * }
     * }
     */
    public function createExternalContact($linkName, $userIds)
    {
        $token = $this->app->access_token->getToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition/create_link?access_token={$token['access_token']}";
        $result = $this->client->post($url, [
            'json' => [
                "link_name" => $linkName,
                "range" => [
                    'user_list' => $userIds
                ],
                'skip_verify' => true
            ]
        ]);
        return json_decode($result->getBody()->getContents(), true);
    }
    public function updateExternalContact($linkName, $userIds,$linkId)
    {
        $token = $this->app->access_token->getToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition/create_link?access_token={$token['access_token']}";
        $result = $this->client->post($url, [
            'json' => [
                "link_id"=>$linkId,
                "link_name" => $linkName,
                "range" => [
                    'user_list' => $userIds
                ],
                'skip_verify' => true
            ]
        ]);
        return json_decode($result->getBody()->getContents(), true);
    }
    public function deleteExternalContact($linkId)
    {
        $token = $this->app->access_token->getToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition/delete_link?access_token={$token['access_token']}";
        $result = $this->client->post($url, [
            'json' => [
                "link_id"=>$linkId,
            ]
        ]);
        return json_decode($result->getBody()->getContents(), true);
    }

}
